/**
 * Created by zhaocong on 2016/7/18.
 * 库存
 */
define(['timepicker', 'tker-css', 'calendar'], function (require, exports, module) {
  "use strict";
  module.exports = new function () {

    /**
     * 时间插件
     */
    $('.form_datetime').datetimepicker({
      language: 'zh-CN',
      weekStart: 1,
      todayBtn: 1,
      autoclose: 1,
      todayHighlight: 1,
      startView: 2,
      forceParse: 0,
      showMeridian: 1,
      minView: 2,
      format: "yyyy-mm-dd"
    });

    // 选择的时间
    var selday = function (tag) {
      var seld = [];
      $('.' + tag).calendar({
        width: 280,
        onSelected: function (view, date, data) {
          var year = date.getFullYear();
          var MM = date.getMonth() + 1;
          var dat = date.getDate();
          var d = year + '-' + MM + '-' + dat;
          if (seld.indexOf(d) < 0) {
            seld.push(d);
            $('#' + tag).val(seld);
            $('.invent-datelist[data-id="' + tag + '"]').append('<li class="list-group-item">' + d + '<i class="fa fa-close seld-x"></i></li>');
          }
        }
      });
      // 移除选择的时间
      $('.invent-datelist').on('click', '.seld-x', function () {
        var par = $(this).parent();
        seld.splice(seld.indexOf(par.text()), 1);
        $('#' + tag).val(seld);
        par.remove();
      });
    };
    (function (selday) {
      var i = 1;
      while (i < 7) {
        selday('ci' + i);
        i++;
      }
    })(selday);


    var app = angular.module('inventApp', []);
    app.controller('inventCtrl', ['$scope', function ($scope) {

      /**
       * 获取服务器数据
       * @type {Date}
       */
      $scope.data = window.data;

      // 时间表
      var now = new Date($scope.data.time);
      $scope.year = now.getFullYear();
      $scope.month = now.getMonth() + 1;
      $scope.weekName = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

      // 月份列表
      $scope.monthLink = [];
      for (var i = $scope.month - 4; i < $scope.month + 3; i++) {
        $scope.monthLink.push(new Date(now.setMonth(i)).getMonth() + 1);
      }

      // 格式日历
      var f = function (a, g) {
        var g = g || 'y/m/d',
            date = new Date(a),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            d = date.getDate(),
            m = m < 10 ? '0' + m : m,
            d = d < 10 ? '0' + d : d;
        return g.replace(/y/, y).replace(/m/, m).replace(/d/, d);
      };

      // 每天
      $scope.day = {};
      // 制表
      $scope.tableCol = [];
      var table = function () {
        var a = new Date($scope.year, $scope.month - 1, 0), // 上个月最后一天
            thisM = new Date($scope.year, $scope.month, 0), // 本月
            nextM = new Date($scope.year, $scope.month + 1, 0), // 下个月
            l = thisM.getDate(), // 本月最大天数
            b = a.getDay(),
            h = a.getDate() - b - 1,
            k = 0,
            n = 0,
            firstday = b + 1,
            trRow = b < 6 ? Math.ceil((l + firstday) / 7) : Math.ceil((l + firstday) / 7) - 1,
            j = 0,
            i = 0;

        for (i = 0; i < trRow; i++) { // 循环行数
          var row = [];
          for (j = 0; j < 7; j++) { // 星期
            var day = {};
            if (i == 0 && b < 6 && j <= b) {
              day.i = ++h;
              day.dis = true;
              day.id = f(a.setDate(day.i));
            } else {
              n++;
              if (n <= l) { // 循环本月
                day.i = n;
                day.id = f(thisM.setDate(day.i));
              } else {
                day.i = ++k;
                day.dis = true;
                day.id = f(nextM.setDate(day.i));
              }
            }
            // 将服务器上的属性赋值到该对象
            $scope.data.days[day.id] && (day.de = 1) && $.extend(day, $scope.data.days[day.id]);
            $scope.day[day.id] = day;
            row[j] = day;
          }
          $scope.tableCol.push(row);
        }
      };
      table();

      // 备份一份原始数据
      $scope.dayold = angular.copy($scope.day);

      /**
       * 表格操作
       */
      $scope.ity = {
        // 上架操作
        sj: function (i, sj) {
          var data = {date: i, sj: sj};
          $.ajax({
            url: '../../data/com.php',
            type: 'post',
            data: data,
            success: function () {
              console.log('上架' + sj);
              $scope.day[i].sj = sj;
              $scope.$digest();
            },
            error: function (err) {
              console.log(err);
            }
          });
        },
        // 保存当天数据
        save: function (data) {
          data.proId = $scope.data.id;
          $.ajax({
            url: '../../data/com.php',
            type: 'post',
            data: data,
            success: function () {
              console.log(data);
              $scope.dayold[data.id] = angular.copy(data);
              $scope.$digest();
            },
            error: function (err) {
              console.log(err);
            }
          });
        },
        // 取消保存
        reset: function (id) {
          $scope.day[id] = angular.copy($scope.dayold[id]);
        },
        // 库存计算 计划不能大于已收
        kcAdd: function (id) {
          $scope.day[id].kc.jh++;
        },
        kcSub: function (id) {
          $scope.day[id].kc.jh > $scope.day[id].kc.ys && $scope.day[id].kc.jh > 0 && $scope.day[id].kc.jh--;
        },
        kcjh: function (id) {
          $scope.day[id].kc.jh < $scope.day[id].kc.ys && ($scope.day[id].kc.jh = $scope.day[id].kc.ys);
          $scope.day[id].kc.sy = $scope.day[id].kc.jh - $scope.day[id].kc.ys;
        }
      };

      // 页面载入完成后去掉mask
      $scope.rmMask = function (last) {
        last && $('.content-mask').hide();
      };

      // 成团操作
      $scope.chengt = function (id) {
        console.log(id);
        $('#chengtModal').modal();
      };

      // 添加收费项
      $scope.priceCate = [];
      $scope.priceCateAdd = function () {
        $scope.priceCate.push({});
      };
      // 移除收费项
      $scope.priceCateRemove = function (i) {
        $scope.priceCate.splice(i, 1);
      };

    }]);
    angular.bootstrap(document.body, ['inventApp']);
  };
});